/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.manage.order;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.services.manage.order.OrderService;
import shop.services.manage.order.bean.Order;
import shop.services.manage.orderdetail.OrderdetailService;
import shop.services.manage.orderdetail.bean.Orderdetail;
import shop.services.manage.product.ProductService;
import shop.services.manage.product.bean.Product;
import shop.services.manage.record.RecordService;
import shop.services.manage.record.bean.Record;
import shop.services.manage.spec.SpecService;
import shop.services.manage.spec.bean.Spec;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;
import shop.services.manage.voucherhave.bean.Voucherhave;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @类名称：OrderAction
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/order/")
public class OrderAction extends BaseController<Order> {
    private final static String RECORT_TYANSTYPE_SUB_INORDER = "2";
    private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SpecService specService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private UserService userService;
    private static final String page_toList = "/manage/order/orderList";
    private static final String page_toEdit = "/manage/order/orderEdit";
    private static final String page_toTakeOutOrder = "/manage/order/takeOutOrder";
    private static final String page_toTakeOutDetail = "/manage/order/takeOutDetail";

    public OrderService getService() {
        return orderService;
    }

    private OrderAction() {
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = page_toEdit;
    }

    /**
     * 跳转到外卖订单列表页面
     *
     * @return
     */
    @RequestMapping("toTakeOutOrder")
    public String toTakeOutOrder() {
        return page_toTakeOutOrder;
    }

    /**
     * 跳转到外卖订单详情页面
     *
     * @return
     */
    @RequestMapping("toTakeOutDetail")
    public String toTakeOutDetail(@ModelAttribute("e") Order order, ModelMap model) {
        order = orderService.selectOne(order);
        model.addAttribute("e", order);
        return page_toTakeOutDetail;
    }

    /**
     * 跳转到线下订单详情页面
     *
     * @return
     */
    @Override
    public String toEdit(Order order, ModelMap model) throws Exception {
        order = orderService.selectOne(order);
        model.addAttribute("e", order);
        return page_toEdit;
    }

    /**
     * 查詢订单列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectOrderList")
    @ResponseBody
    public JSONResult selectOrderList(Order order) throws Exception {
        List<Order> orderList = orderService.selectOrderList(order);
        jsonResult = new JSONResult();
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 查詢订单列表
     *
     * @param request 请求
     * @param order       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectOrderPage")
    @ResponseBody
    public PagerModel selectOrderPage(HttpServletRequest request, Order order) {
        int offset = 0;
        int pageSize = 10;
        int start=Integer.parseInt(request.getParameter("start"));
        int length= Integer.parseInt(request.getParameter("length"));
        if(start>0)
            offset=start;
        if(length>0)
            pageSize=length;
        order.setOffset(offset);
        order.setPageSize(pageSize);
        //查詢订单列表
        PagerModel pager = orderService.selectOrderPage(order);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 订单商品发货处理
     *
     * @param e
     * @return
     */
    @RequestMapping("sendProduct")
    public String sendProduct(Order e) {
        //确认收货
        if (e.getStatus().equals("已发货")) {
            e.setStatus("finish");
            orderService.update(e);
        }
        //商品发货
        if (e.getStatus().equals("待发货")) {
            e.setStatus("send");
            orderService.update(e);
        }
        return page_toList;
    }

    /**
     * 批量删除订单及对应的订单详情
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "deletesOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deletesOrderDetail(@RequestParam(value = "ids[]") String[] ids) {
        JSONResult jsonResult = new JSONResult();
        Orderdetail orderdetail = new Orderdetail();
        if (ids == null || ids.length == 0) {
            throw new NullPointerException("请选择需要删除订单！");
        } else {
            Order order = new Order();
            for (int i = 0; i < ids.length; i++) {
                orderdetail.setOrderID(ids[i]);
                List<Orderdetail> orderdetails = orderdetailService.selectList(orderdetail);
                for (Orderdetail orderdetailOne : orderdetails) {
                    orderdetailService.delete(orderdetailOne);
                }
                order.setId(ids[i]);
                orderService.delete(order);
            }
            jsonResult.setSuccess(true);
        }
        return jsonResult;
    }

    /**
     * 删除单个订单及对应的订单详情
     */
    @RequestMapping(value = "deleteOne", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteOne(String id) {
        JSONResult jsonResult = new JSONResult();
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(id);
        /*删除该订单所有的订单详情*/
        List<Orderdetail> orderdetails = orderdetailService.selectList(orderdetail);
        for (Orderdetail orderdetailOne : orderdetails) {
            orderdetailService.delete(orderdetailOne);
        }
        Order order = new Order();
        order.setId(id);
        orderService.delete(order);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 订单详情商品列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectOrderDetail")
    @ResponseBody
    public JSONResult selectOrderDetail(Orderdetail orderdetail) throws Exception {
        List<Orderdetail> orderdetailList = orderdetailService.selectOrderDetail(orderdetail);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setData(orderdetailList);
        return jsonResult;
    }

    /**
     * 确认付款（线下支付）
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateOrderStatus", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateOrderStatus(Order order) throws Exception {
        JSONResult jsonResult = new JSONResult();
        orderService.update(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        //查询订单详情列表
        List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
        //遍历订单详情
        for (Orderdetail OrdedetailInfo : orderdetailList) {
            //查询商品信息
            Product product = new Product();
            product.setId(OrdedetailInfo.getProductID());
            product = productService.selectOne(product);
            //更新平台商品库存
            Spec spec = new Spec();
            spec.setProductID(OrdedetailInfo.getProductID());
            spec.setCombination(OrdedetailInfo.getSpecInfo());
            spec = specService.selectOne(spec);
            spec.setStock(spec.getStock() - OrdedetailInfo.getNumber());
            specService.update(spec);
            //更新平台商品销售量
            product.setSellcount(product.getSellcount() + OrdedetailInfo.getNumber());
            productService.update(product);
        }
        //更新买家个人数据
        User buyer = new User();
        buyer.setId(order.getUserID());
        buyer = userService.selectOne(buyer);
        BigDecimal score =buyer.getScore().add(order.getPtotal());
        buyer.setScore(score);
        userService.update(buyer);
        //买家上级数据更新
        if (!"0".equals(buyer.getPid())) {
            //上级返利
            User supUser = new User();
            supUser.setId(buyer.getPid());
            supUser = userService.selectOne(supUser);
            BigDecimal brokerage=order.getOtotal().multiply(new BigDecimal("0.2"));
            brokerage=brokerage.setScale(2, BigDecimal.ROUND_HALF_UP);
            logger.debug("返利金额"+brokerage);
            BigDecimal income=supUser.getIncome().add(brokerage);
            logger.debug("用户收益"+income);
            supUser.setIncome(income);
            userService.update(supUser);
            //上级交易记录
            Record recordInfo = new Record();
            recordInfo.setUserID(supUser.getId());
            recordInfo.setTransType(RECORT_TYANSTYPE_SUB_INORDER);
            recordInfo.setTransID(order.getId());
            recordInfo.setMoney(order.getOtotal().multiply(new BigDecimal("0.2")));
            recordService.insert(recordInfo);
        }
        return jsonResult;
    }

}
